import Common from "./Common";
import Wx, {wx} from "../wx/Wx";

export default class LocalStorage {
    public static setBoolean(_key: string, _value: boolean) {
        cc.sys.localStorage.setItem(_key, _value.toString());
    }

    public static getBoolean(_key: string, _def?: boolean): boolean {
        let def = _def;

        if (!def) {
            def = false;
        }
        const ret = cc.sys.localStorage.getItem(_key) as string;
        if (ret == null || ret.length == 0) {
            return def;
        }
        return ret == "true";
    }

    public static setInt(_key: string, _value: number) {
        cc.sys.localStorage.setItem(_key, Math.round(_value).toString());
    }

    public static getInt(_key: string, _def?: number): number {
        let def = _def;
        if (!def) {
            def = 0;
        }
        const ret = cc.sys.localStorage.getItem(_key) as string;
        if (ret == null || ret.length == 0) {
            return Math.round(def);
        }
        return parseInt(ret);
    }

    public static setFloat(_key: string, _value: number) {
        cc.sys.localStorage.setItem(_key, _value.toString());
    }

    public static getFloat(_key: string, _def?: number): number {
        let def = _def;
        if (!def) {
            def = 0;
        }
        const ret = cc.sys.localStorage.getItem(_key) as string;
        if (ret == null || ret.length == 0) {
            return def;
        }
        return parseFloat(ret);
    }

    public static setString(_key: string, _value: string) {
        cc.sys.localStorage.setItem(_key, _value);
    }

    public static getString(_key: string, _def?: string): string {
        let def = _def;
        if (!def) {
            def = "";
        }
        const ret = cc.sys.localStorage.getItem(_key) as string;
        if (!ret || ret.length == 0) {
            return def;
        }
        return ret;
    }

    public static async setObj<T>(_key: string, _value: T) {
        if (!_value) {
            cc.sys.localStorage.setItem(_key, "{}");
            return;
        }
        cc.sys.localStorage.setItem(_key, JSON.stringify(_value));
    }

    /**
     * 传入default, 会生成T的完整实例,而不是一个兼容的json对象.
     * @param {string} _key
     * @param {T} def
     * @returns {T}
     */
    public static getObj<T>(_key: string, def?: T): T {
        const ret = cc.sys.localStorage.getItem(_key) as string;
        if (!ret || ret.length == 0) {
            return def;
        } else if (def) {
            return Common.deepAssign(true, def, JSON.parse(ret) as T);
        } else {
            return JSON.parse(ret) as T;
        }
    }

    public static remove(_key: string) {
        cc.sys.localStorage.removeItem(_key);
    }

    // 清空本地数据.用于开发版本
    public static clear() {
        if (cc.sys.localStorage.clear) {
            cc.sys.localStorage.clear()
        }
        if (Wx.isWeChatEnv()) {
            wx.clearStorageSync()
        }
    }
}
